import 'package:OASys/api/AnnouncementApi.dart';
import 'package:OASys/components/FormComponents.dart';
import 'package:OASys/components/scaffoldItem.dart';
import 'package:OASys/entity/AnnouncementVo.dart';
import 'package:flutter/material.dart';

class AnnouncementEditPage extends StatelessWidget {
  final Map arguments;

  AnnouncementEditPage({Key key, this.arguments});
  @override
  Widget build(BuildContext context) {
    return ScaffoldItem(
        '通知公告信息',
        AnnouncementEdit(
          announcementId:
              arguments['info'] == null ? -1 : arguments['info']['id'],
          isEdit: arguments['isEdit'],
        ));
  }
}

class AnnouncementEdit extends StatefulWidget {
  final int announcementId;
  final bool isEdit;

  AnnouncementEdit({Key key, this.announcementId, this.isEdit});

  @override
  _AnnouncementEditState createState() => _AnnouncementEditState();
}

class _AnnouncementEditState extends State<AnnouncementEdit> {
  GlobalKey<FormState> formKey = GlobalKey<FormState>();
  AnnouncementVo announcementVo;
  AnnouncementVo info;
  List<Map<String, dynamic>> typeList = [];
  bool enabled;

  @override
  void initState() {
    super.initState();
    print(widget.announcementId);
    print(widget.isEdit);
    enabled = widget.isEdit;
    buildTypeList();
    if (widget.announcementId == -1) {
      setState(() {
        info = new AnnouncementVo();
        announcementVo = new AnnouncementVo();
      });
    } else {
      getAnnouncementInfo(widget.announcementId);
    }
  }

  void getAnnouncementInfo(int id) {
    AnnouncementApi().info(id, success: (res) {
      setState(() {
        announcementVo = res;
        info = res;
      });
    }, error: (err) {
      print(err.code);
      showFailMessage(context);
    });
  }

  // 单选框
  selectOne() {
    showOneSelect(context, info.type);
  }

  void buildTypeList() {
    setState(() {
      typeList.add({"key": 0, "value": "通知"});
      typeList.add({"key": 1, "value": "公告"});
    });
  }

  //保存操作
  void save() {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        print(info.toJson().toString());
        doSave(info);
      });
    }
  }

  // 发起保存请求
  void doSave(AnnouncementVo info) {
    print('doSave');
    AnnouncementApi().save(
      info,
      success: (res) {
        Navigator.of(context).pop(true);
      },
      error: (err) {
        print(err.code);
        showFailMessage(context);
      },
    );
  }

  // 重置表单
  void reset() {
    var form = formKey.currentState;
    form.reset();
    setState(() {
      info = AnnouncementVo.fromJson(announcementVo.toJson());
    });
  }

  @override
  Widget build(BuildContext context) {
    if (info == null || announcementVo == null) {
      return Container(
        child: Text('加载中'),
      );
    } else {
      return SingleChildScrollView(
        child: Container(
          width: 500,
          margin: EdgeInsets.all(10),
          child: Card(
            child: Container(
              margin: EdgeInsets.all(10),
              child: Form(
                key: formKey,
                child: Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('通知公告名称：'),
                        FormInput(
                          enabled: enabled,
                          initValue: announcementVo.name,
                          hintText: "请输入通知公告名称",
                          validator: (content) {
                            if (content.length > 15) {
                              return "通知公告称名过长";
                            } else if (content.length <= 0) {
                              return "通知公告称过短";
                            }
                          },
                          onSave: (value) {
                            info.name = value;
                          },
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('通知公告类型：'),
                        Container(
                          width: 200,
                          height: 50,
                          alignment: Alignment.centerLeft,
                          child: FlatButton(
                            minWidth: 200,
                            onPressed: () {
                              if (!enabled) {
                                return;
                              }
                              selectOne();
                            },
                            child: Container(
                              alignment: Alignment.centerLeft,
                              child: Text(
                                info.type == null ? "请选择通知公告类型" : info.typeName,
                                style: TextStyle(
                                  color: Colors.black,
                                  fontSize: 16,
                                  letterSpacing: 1,
                                ),
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        PrefixContanier('通知公告内容：'),
                        FormText(
                          enabled: enabled,
                          initValue: announcementVo.content,
                          hintText: "请输入通知公告内容",
                          validator: (content) {
                            if (content.length > 300) {
                              return "通知公告内容过长";
                            } else if (content.length <= 0) {
                              return "通知公告过短";
                            }
                          },
                          onSave: (value) {
                            info.content = value;
                          },
                        ),
                      ],
                    ),
                    Visibility(
                      visible: enabled,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                        children: [
                          RaisedButton(
                            color: Color.fromRGBO(33, 150, 243, 1),
                            onPressed: save,
                            child: Text(
                              "保 存",
                              style: TextStyle(color: Colors.white),
                            ),
                          ),
                          RaisedButton(
                            color: Color.fromRGBO(103, 194, 58, 1),
                            onPressed: reset,
                            child: Text(
                              "重 置",
                              style: TextStyle(color: Colors.white),
                            ),
                          )
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ),
      );
    }
  }

  // 显示单选
  showOneSelect(BuildContext context, int oldType) {
    int type = oldType;
    String typeName;

    Widget bulidListItem(int index, StateSetter setState) {
      return Row(
        children: [
          Flexible(
            child: RadioListTile(
              title: Text(typeList[index]["value"]),
              value: index,
              groupValue: type,
              onChanged: (value) {
                setState(() {
                  type = value;
                  typeName = typeList[index]["value"];
                  info.type = value;
                  info.typeName = typeList[index]["value"];
                });
              },
            ),
          ),
        ],
      );
    }

    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            titlePadding: EdgeInsets.all(0),
            title: Container(
              height: 50,
              alignment: Alignment.center,
              child: Text(
                '类型选择',
                style: TextStyle(color: Colors.white),
              ),
              decoration: BoxDecoration(
                color: Colors.blue,
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(3),
                  topRight: Radius.circular(3),
                ),
              ),
            ),
            contentPadding: EdgeInsets.all(0),
            content: new StatefulBuilder(
              builder: (context, StateSetter setState) {
                return Container(
                  height: 300,
                  width: 300,
                  decoration: BoxDecoration(
                    color: Color.fromRGBO(250, 250, 250, 1),
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Column(
                    children: [
                      Container(
                        margin: EdgeInsets.only(
                          top: 20,
                          bottom: 20,
                        ),
                        height: 260,
                        width: 200,
                        child: ListView.builder(
                            itemCount: typeList.length,
                            itemBuilder: (context, index) {
                              return bulidListItem(index, setState);
                            }),
                      ),
                    ],
                  ),
                );
              },
            ),
            actions: <Widget>[
              RaisedButton(
                color: Color.fromRGBO(33, 150, 243, 1),
                child: Text("保 存"),
                onPressed: () {
                  Navigator.of(context).pop(true);
                },
              ),
            ],
          );
        }).then((value) {
      print(value);
      if (value != null && value) {
        setState(() {
          info.type = type;
          info.typeName = typeName;
        });
      }
    });
  }
}
